import time
import threading
import sys
import nls


URL="wss://nls-gateway.cn-shanghai.aliyuncs.com/ws/v1"
AKID="LTAIdOGQXo1FtkTn"
AKKEY="3NlvLq7UH8nDxY5tuOdT1rm1mjY1wM"
APPKEY="mV7BpVBMpZMvkQSn"

#以下代码会根据音频文件内容反复进行一句话识别
class VoiceRecognition:
    def __init__(self, tid, test_file):
        self.__th = threading.Thread(target=self.__test_run)
        self.__id = tid
        self.__test_file = test_file
        self.asr_string = ""
   
    def loadfile(self, filename):
        with open(filename, "rb") as f:
            self.__data = f.read()
    
    def start(self):
        self.loadfile(self.__test_file)
        self.__th.start()

    def test_on_start(self, message, *args):
        print("test_on_start:{}".format(message))

    def test_on_error(self, message, *args):
        print("on_error args=>{}".format(args))

    def test_on_close(self, *args):
        print("on_close: args=>{}".format(args))

    def test_on_result_chg(self, message, *args):
        print("test_on_chg:{}".format(message))

    def test_on_completed(self, message, *args):
        print("on_completed:args=>{} message=>{}".format(args, message))
        self.asr_string = message


    def __test_run(self):
        print("thread:{} start..".format(self.__id))
        
        sr = nls.NlsSpeechRecognizer(
                    url=URL,
                    akid=AKID,
                    aksecret=AKKEY,
                    appkey=APPKEY,
                    on_start=self.test_on_start,
                    on_result_changed=self.test_on_result_chg,
                    on_completed=self.test_on_completed,
                    on_error=self.test_on_error,
                    on_close=self.test_on_close,
                    callback_args=[self.__id]
                )
    
        print("{}: session start".format(self.__id))
        r = sr.start(aformat="pcm", ex={"hello":123})
       
        self.__slices = zip(*(iter(self.__data),) * 640)
        for i in self.__slices:
            sr.send_audio(bytes(i))
            time.sleep(0.01)

        r = sr.stop()
        print("{}: sr stopped:{}".format(self.__id, r))
        

# def multiruntest(num=500):
#     for i in range(0, num):
#         name = "thread" + str(i)
#         t = TestSr(name, "output_one_channel.wav")
#         t.start()
# 
# #设置打开日志输出
# nls.enableTrace(False)
# multiruntest(1)
